package com.yq.master.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yq.core.base.service.BaseService;
import com.yq.core.entity.SysPowerEntity;
import com.yq.core.service.SysPowerService;
import com.yq.core.util.Result;
import com.yq.master.annotation.AzerothAutowired;
import com.yq.master.bean.WebUserBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 信  息: [yinquan] [2017-03-04] [1.2];
 * 描  述: 信息状态返回类，同意使用此类返回数据
 */
@Controller
@RequestMapping(value = "/sys/menu")
public class SysMenuController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysMenuController.class);

    @AzerothAutowired
    public SysPowerService sysPowerService;

    protected BaseService getServcie() {
        return sysPowerService;
    }

    protected String getJumpData() {
        return "";
    }

    /*****************************************************************************************/

    /** 获取菜单树 **/
    @RequestMapping(value = "menuTree",params="_m=load")
    @ResponseBody
    public Object menuTreeLoad(Model model, ServletRequest request) {

        List<Map<String, Object>> resultList = Lists.newArrayList();
        Map<String, Object> parameter = Maps.newHashMap();

        Result result = isCheck(request);

        String funType = request.getParameter("funType");
        String all = request.getParameter("all");
        String parentUid = request.getParameter("parentUid");

        // 校验权限标识
        if(StringUtils.isBlank(funType)) {
            result.resoutError("权限标识不能为空");
            return result;
        }
        if(funType.equals("top")) {
            parameter.put("funType", "0");
        } else if(funType.equals("left")) {
            parameter.put("funType", "1");
        } else if(funType.equals("fun")) {
            parameter.put("funType", "2");
        } else {
            result.resoutError("权限标识错误");
            return result;
        }

        if(StringUtils.isNotBlank(parentUid)) {
            parameter.put("parentUid", parentUid);
        }

        // 获取菜单
        List<Map<String, Object>> list = sysPowerService.findMenuTopList(parameter);

        // 查看是否显示全部选项
        if(all!=null && all.equals("search")) {
            setResulMenu(resultList, "", "全部", true);
        }

        for(int i=list.size()-1; i>=0; i--) {
            Map<String, Object> menuTop = list.get(i);
            setResulMenu(resultList, menuTop.get("uid").toString(), menuTop.get("funName").toString(), false);
        }
        return resultList;
    }

    /** 获取顶部菜单 **/
    @RequestMapping(value = "menuTop",params="_m=load")
    @ResponseBody
    public Object menuTopLoad(Model model, ServletRequest request) {

        Result result = new Result();
        Map<String, Object> parameter = Maps.newHashMap();

        parameter.put("funType", "0");

        List<Map<String, Object>> list = sysPowerService.findMenuTopList(parameter);
        result.setData(list);
        return result;
    }

    /** 获取左侧菜单 **/
    @RequestMapping(value = "menuLeft",params="_m=load")
    @ResponseBody
    public Object menuLeftLoad(Model model, ServletRequest request) {

        // 搜索顶部菜单
        String type= request.getParameter("type");
        String all= request.getParameter("all");
        String rootUid= "11a9a388727911e7929d00e04c0cea5f";//request.getParameter("rootUid");
        Map<String, Object> parameter = Maps.newHashMap();
        parameter.put("rootUid", rootUid);

        /*if(type!=null && type.equals("combobox")) {
            return getMenu(type, all, parameter);
        }*/

        List<Map<String, Object>> list = sysPowerService.findMenuLeftList(parameter);
        List<Map<String, Object>> tree = Lists.newArrayList();
        Map<String, Integer> indexMap = Maps.newHashMap();

        for(int i=0; i<list.size(); i++) {
            Map<String, Object> map = list.get(i);
            map.put("id", map.get("uid").toString());

            if(map.get("funType").toString().equals("1")) {
                indexMap.put(map.get("uid").toString(), i);

            } else if(map.get("funType").toString().equals("2")) {
                if(indexMap.get(map.get("parentUid").toString())==null) {
                    continue;
                }

                int indexList = indexMap.get(map.get("parentUid").toString());
                Map<String, Object> info = list.get(indexList);

                List<Map<String, Object>> infoList = Lists.newArrayList();
                if(info.get("children")!=null) {
                    infoList = (List<Map<String, Object>>) info.get("children");
                }
                infoList.add(map);
                info.put("children", infoList);
            }
        }

        for(int i=0; i<list.size(); i++) {
            Map<String, Object> map = list.get(i);
            if(map.get("funType").toString().equals("2")) {
                break;
            }
            map.remove("parentUid");
            map.remove("relOrder");

            if(map.get("children")!=null) {
                map.put("state", "closed");
            }
            tree.add(map);
        }

        return tree;
    }


    /*****************************************************************************************/
    /** 排序菜单 **/
    @RequestMapping(value = "order",params="_m=exec")
    @ResponseBody
    public Object orderExec(Model model, ServletRequest request) {
        Map<String, Object> parameters = Maps.newHashMap();
        Result result = isCheck(request);

        try{
            // 排序类型
            String type = request.getParameter("type");
            if(StringUtils.isBlank(type)) {
                result.resoutError("排序类型不能为空");
                return result;
            }

            if(!type.equals("0") && !type.equals("1") && !type.equals("2")) {
                result.resoutError("排序类型错误");
                return result;
            }

            // 上移或者下移动
            String orderFunType = request.getParameter("orderFunType");
            if(StringUtils.isBlank(orderFunType)) {
                result.resoutError("排序标识不能为空");
                return result;
            }

            if(!orderFunType.equals("up") && !orderFunType.equals("down")) {
                result.resoutError("排序标识错误");
                return result;
            }

            parameters.put("uid", getUid(request));
            parameters.put("nextuid", request.getParameter("nextuid"));
            parameters.put("funType", type);
            parameters.put("updateBy", "system");
            parameters.put("orderFunType", orderFunType);
            sysPowerService.updateOrder(parameters);

            result.resoutSucess("操作成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            result.resoutError("操作失败");
        }

        return result;
    }

    /** 冻结菜单 - 顶部 **/
    @RequestMapping(value = "lockTop",params="_m=exec")
    @ResponseBody
    public Object lockTopExec(Model model, ServletRequest request) {
        return lockMenu(request, "1");
    }

    /** 解冻菜单 - 顶部 **/
    @RequestMapping(value = "unlockTop",params="_m=exec")
    @ResponseBody
    public Object unlocTopkExec(Model model, ServletRequest request) {
        return lockMenu(request, "0");
    }

    /** 冻结菜单 - 左侧 **/
    @RequestMapping(value = "lockLeft",params="_m=exec")
    @ResponseBody
    public Object lockLeftExec(Model model, ServletRequest request) {
        return lockMenu(request, "1");
    }

    /** 解冻菜单 - 左侧 **/
    @RequestMapping(value = "unlockLeft",params="_m=exec")
    @ResponseBody
    public Object unlockLeftExec(Model model, ServletRequest request) {
        return lockMenu(request, "0");
    }

    /** 冻结菜单 - 模块 **/
    @RequestMapping(value = "lockFun",params="_m=exec")
    @ResponseBody
    public Object lockFunExec(Model model, ServletRequest request) {
        return lockMenu(request, "1");
    }

    /** 解冻菜单 - 模块 **/
    @RequestMapping(value = "unlockFun",params="_m=exec")
    @ResponseBody
    public Object unlockFunExec(Model model, ServletRequest request) {
        return lockMenu(request, "0");
    }

    /** 冻结菜单 - 功能 **/
    @RequestMapping(value = "lockPower",params="_m=exec")
    @ResponseBody
    public Object lockPowerExec(Model model, ServletRequest request) {
        return lockMenu(request, "1");
    }

    /** 解冻菜单 - 功能 **/
    @RequestMapping(value = "unlockPower",params="_m=exec")
    @ResponseBody
    public Object unlockPowerExec(Model model, ServletRequest request) {
        return lockMenu(request, "0");
    }

    /*****************************************************************************************/
    /** 设置下拉菜单选项 **/
    private void setResulMenu(List<Map<String, Object>> resultList, String uid, String funName, boolean select) {
        Map<String, Object> resulMenu = Maps.newHashMap();
        resulMenu.put("uid", uid);
        resulMenu.put("funName", funName);
        if(select) {
            resulMenu.put("selected", true);
        }
        resultList.add(resulMenu);
    }

    /** 冻结、解冻菜单 **/
    private Object lockMenu(ServletRequest request, String type) {
        Map<String, Object> parameters = Maps.newHashMap();
        Result result = isCheck(request);
        Date date = new Date();

        try {
            WebUserBean webUserBean = getWebUserBean(request);
            SysPowerEntity sysPowerEntity = sysPowerService.findUniqueById(getUid(request));
            sysPowerEntity.setLockStatus(type);
            sysPowerEntity.setUpdateBy(webUserBean.getUid());
            sysPowerEntity.setUpdateAt(date);

            sysPowerService.update(sysPowerEntity);

            result.resoutSucess("操作成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            result.resoutError("操作失败");
        }

        return result;
    }
}
